<template>
  <div class="salesman-dashboard">
    <el-card>
      <h2>销售仪表盘</h2>
      <p>欢迎使用销售管理系统，这里展示了销售相关的统计数据和图表。</p>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header-with-icon">
              <el-icon><ShoppingCart /></el-icon>
              <span>最近7天订单数量</span>
            </div>
          </template>
          <div class="statistic-value">{{ statistics.monthlyOrders }}</div>
          <div class="statistic-label">
            {{ getStatisticLabel('orders') }}
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header-with-icon">
              <el-icon><Money /></el-icon>
              <span>最近7天销售额</span>
            </div>
          </template>
          <div class="statistic-value">¥{{ statistics.monthlySales.toLocaleString() }}</div>
          <div class="statistic-label">
            {{ getStatisticLabel('sales') }}
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header-with-icon">
              <el-icon><User /></el-icon>
              <span>活跃客户</span>
            </div>
          </template>
          <div class="statistic-value">{{ statistics.activeCustomers }}</div>
          <div class="statistic-label">{{ getStatisticLabel('customers') }} {{ statistics.newCustomers }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 热销商品表格 -->
    <el-card class="hot-products-card">
      <template #header>
        <div class="card-header">
          <span>热销商品排行</span>
          <el-radio-group v-model="hotProductsTimeRange" size="small" @change="fetchHotProducts">
            <el-radio-button label="week">本周</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <el-table :data="hotProducts" style="width: 100%" v-loading="hotProductsLoading">
        <el-table-column type="index" label="排名" width="100" align="center" />
        <el-table-column prop="name" label="商品名称" min-width="80"  align="center"/>
        <el-table-column label="类别" width="160" align="center">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.category)">
              {{ row.category }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="销量" width="100" align="center">
          <template #default="{ row }">
            {{ row.sales }}{{ row.unit }}
          </template>
        </el-table-column>
        <el-table-column label="销售额" width="120" align="center">
          <template #default="{ row }">
            ¥{{ row.amount.toLocaleString() }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 销售趋势图表 -->
    <el-card class="trend-chart-card">
      <template #header>
        <div class="card-header">
          <span>销售趋势</span>
          <el-radio-group v-model="salesTrendTimeRange" size="small" @change="fetchSalesTrend">
            <el-radio-button label="week">最近7天</el-radio-button>
            <el-radio-button label="month">最近30天</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <div class="chart-container" v-loading="salesTrendLoading">
        <v-chart class="chart" :option="salesTrendOption" autoresize />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  DataZoomComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import {
  ShoppingCart,
  Money,
  User,
  Goods
} from '@element-plus/icons-vue'
import axios from 'axios'
import { getToken } from '@/utils/auth'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  DataZoomComponent
])

// 配置 axios 默认值
axios.defaults.baseURL = 'http://localhost:8000'
axios.defaults.timeout = 15000
axios.defaults.withCredentials = true

// 统计数据
const statistics = ref({
  monthlyOrders: 0,
  orderGrowth: 0,
  monthlySales: 0,
  salesGrowth: 0,
  activeCustomers: 0,
  newCustomers: 0
})

// 热销商品数据
const hotProducts = ref([])
const hotProductsLoading = ref(false)
const hotProductsTimeRange = ref('week')

// 销售趋势数据
const salesTrend = ref([])
const salesTrendLoading = ref(false)
const salesTrendTimeRange = ref('week')

// 销售趋势图表选项
const salesTrendOption = ref({
  title: {
    text: '销售趋势分析',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    data: ['订单数量', '销售额', '预测值'],
    bottom: 10
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '15%',
    top: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: [
    {
      type: 'value',
      name: '订单数量',
      position: 'left'
    },
    {
      type: 'value',
      name: '销售额',
      position: 'right',
      axisLabel: {
        formatter: '{value} 元'
      }
    }
  ],
  series: [
    {
      name: '订单数量',
      type: 'bar',
      data: []
    },
    {
      name: '销售额',
      type: 'line',
      smooth: true,
      data: []
    },
    {
      name: '预测值',
      type: 'line',
      smooth: true,
      data: [],
      lineStyle: {
        type: 'dashed'
      },
      itemStyle: {
        color: '#ff9800'
      }
    }
  ]
})

// 获取仪表盘统计数据
const fetchDashboardStats = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.error('未登录或登录已过期')
      return
    }

    const response = await axios({
      method: 'get',
      url: '/api/dashboard/stats/',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.data) {
      // 从后端获取基础统计数据
      const { total_orders, pending_orders, completed_orders } = response.data
      
      // 计算本月订单数据
      await calculateStats()
    }
  } catch (error) {
    console.error('获取仪表盘统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 计算月度统计数据
const calculateStats = async () => {
  try {
    const token = getToken()
    if (!token) return

    // 获取当前日期和上个月同期的日期范围
    const now = new Date()
    const currentYear = now.getFullYear()
    const currentMonth = now.getMonth()
    const lastMonth = currentMonth === 0 ? 11 : currentMonth - 1
    const lastMonthYear = currentMonth === 0 ? currentYear - 1 : currentYear

    // 计算最近7天的日期范围
    const last7Days = new Date(now)
    last7Days.setDate(now.getDate() - 7)
    
    // 计算上一个7天的日期范围（环比）
    const previous7Days = new Date(last7Days)
    previous7Days.setDate(previous7Days.getDate() - 7)
    
    // 计算上个月同期的日期范围（同比）
    const lastMonthSamePeriod = new Date(lastMonthYear, lastMonth, now.getDate() - 7)
    const lastMonthEnd = new Date(lastMonthYear, lastMonth, now.getDate())

    // 获取最近7天的订单
    const recentResponse = await axios({
      method: 'get',
      url: '/api/sales-orders/',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    // 处理订单数据
    const allOrders = recentResponse.data?.data?.items || []
    console.log('获取到的所有订单:', allOrders)

    // 过滤最近7天的有效订单
    const validRecentOrders = allOrders.filter(order => {
      const orderDate = new Date(order.payment_time)
      return orderDate >= last7Days && 
             orderDate <= now && 
             ['paid', 'shipped', 'completed'].includes(order.status)
    })

    // 过滤上一个7天的有效订单
    const validPreviousOrders = allOrders.filter(order => {
      const orderDate = new Date(order.payment_time)
      return orderDate >= previous7Days && 
             orderDate < last7Days && 
             ['paid', 'shipped', 'completed'].includes(order.status)
    })

    // 过滤上个月同期的有效订单
    const validLastMonthOrders = allOrders.filter(order => {
      const orderDate = new Date(order.payment_time)
      return orderDate >= lastMonthSamePeriod && 
             orderDate <= lastMonthEnd && 
             ['paid', 'shipped', 'completed'].includes(order.status)
    })

    console.log('最近7天订单:', validRecentOrders)
    console.log('上一个7天订单:', validPreviousOrders)
    console.log('上个月同期订单:', validLastMonthOrders)

    // 计算最近7天的订单数量
    const recentOrderCount = validRecentOrders.length
    
    // 计算上一个7天的订单数量
    const previousOrderCount = validPreviousOrders.length
    
    // 计算上个月同期的订单数量
    const lastMonthOrderCount = validLastMonthOrders.length
    
    // 计算订单环比增长率
    const orderWoWGrowth = previousOrderCount > 0 
      ? Math.round(((recentOrderCount - previousOrderCount) / previousOrderCount) * 100) 
      : recentOrderCount > 0 ? 100 : 0

    // 计算订单同比增长率
    const orderYoYGrowth = lastMonthOrderCount > 0 
      ? Math.round(((recentOrderCount - lastMonthOrderCount) / lastMonthOrderCount) * 100) 
      : recentOrderCount > 0 ? 100 : 0

    // 计算最近7天的销售额
    const recentSales = validRecentOrders.reduce((sum, order) => {
      const amount = parseFloat(order.total_amount) || 0
      return sum + amount
    }, 0)
    
    // 计算上一个7天的销售额
    const previousSales = validPreviousOrders.reduce((sum, order) => {
      const amount = parseFloat(order.total_amount) || 0
      return sum + amount
    }, 0)
    
    // 计算上个月同期的销售额
    const lastMonthSales = validLastMonthOrders.reduce((sum, order) => {
      const amount = parseFloat(order.total_amount) || 0
      return sum + amount
    }, 0)
    
    // 计算销售额环比增长率
    const salesWoWGrowth = previousSales > 0 
      ? Math.round(((recentSales - previousSales) / previousSales) * 100) 
      : recentSales > 0 ? 100 : 0

    // 计算销售额同比增长率
    const salesYoYGrowth = lastMonthSales > 0 
      ? Math.round(((recentSales - lastMonthSales) / lastMonthSales) * 100) 
      : recentSales > 0 ? 100 : 0

    // 获取本月所有订单用于统计活跃用户
    const currentMonthStart = new Date(now.getFullYear(), now.getMonth(), 1)
    const currentMonthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0)
    
    // 统计客户订单频率
    const customerOrderCount = new Map()
    allOrders.forEach(order => {
      if (order.customer_name && ['paid', 'shipped', 'completed'].includes(order.status)) {
        const count = customerOrderCount.get(order.customer_name) || 0
        customerOrderCount.set(order.customer_name, count + 1)
      }
    })

    // 计算活跃客户（订单量超过1次的客户）
    const activeCustomers = Array.from(customerOrderCount.values()).filter(count => count > 1).length

    // 计算新增客户（最近7天首次下单的客户）
    const recentCustomerNames = new Set(validRecentOrders.map(order => order.customer_name).filter(Boolean))
    const previousCustomerNames = new Set(validPreviousOrders.map(order => order.customer_name).filter(Boolean))
    const newCustomers = Array.from(recentCustomerNames).filter(name => !previousCustomerNames.has(name)).length

    // 更新统计数据
    statistics.value = {
      monthlyOrders: recentOrderCount,
      orderGrowth: orderYoYGrowth, // 同比
      orderWoWGrowth, // 环比
      monthlySales: recentSales,
      salesGrowth: salesYoYGrowth, // 同比
      salesWoWGrowth, // 环比
      activeCustomers,
      newCustomers
    }

    console.log('统计数据更新完成:', statistics.value)
  } catch (error) {
    console.error('计算统计数据失败:', error)
    ElMessage.error('计算统计数据失败')
  }
}

// 获取热销商品数据
const fetchHotProducts = async () => {
  try {
    console.log('fetchHotProducts: 开始获取热销商品数据...')
    hotProductsLoading.value = true
    const token = getToken()
    if (!token) {
      console.error('fetchHotProducts: 未获取到token，请先登录')
      ElMessage.warning('请先登录')
      return
    }
    console.log('fetchHotProducts: 当前选择的时间范围:', hotProductsTimeRange.value)

    // 1. 获取所有商品的基本信息
    console.log('fetchHotProducts: 正在获取商品基本信息...')
    const productsResponse = await axios.get('/api/products', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    console.log('fetchHotProducts: 商品API响应数据:', productsResponse.data)

    // 处理商品数据，创建临时Map
    const productsData = productsResponse.data?.items || 
                        productsResponse.data?.results || 
                        (Array.isArray(productsResponse.data) ? productsResponse.data : [])
    
    console.log('fetchHotProducts: 解析后的商品数据数组长度:', productsData.length)
    console.log('fetchHotProducts: 商品数据示例:', productsData.slice(0, 2))
    
    // 创建商品销售统计Map - 使用商品名称作为键
    const productStatsMap = new Map()
    
    // 初始化每个商品的统计数据
    console.log('fetchHotProducts: 开始初始化商品统计数据...')
    productsData.forEach(product => {
      // 只用 stock_info 数组的 current_stock 字段累加作为库存量
      let totalStock = 0
      if (product.stock_info && Array.isArray(product.stock_info) && product.stock_info.length > 0) {
        totalStock = product.stock_info.reduce((sum, stockItem) => {
          return sum + (parseFloat(stockItem.current_stock) || 0)
        }, 0)
        console.log(`fetchHotProducts: 从stock_info数组计算商品 "${product.name}" 的总库存: ${totalStock}`)
      }
      
      // 处理类别名称
      let categoryName = '';
      let categoryId = null;
      
      // 调试输出类别信息
      console.log('商品类别信息:', {
        category: product.category,
        category_id: product.category_id,
        category_detail: product.category_detail
      });
      
      if (product.category_detail) {
        categoryName = product.category_detail.description?.replace(/类别$/, '') || 
                      product.category_detail.name?.replace(/类别$/, '') || '未分类';
        categoryId = product.category_detail.id;
      } else if (product.category) {
        categoryName = typeof product.category === 'string' ? 
                      product.category.replace(/类别$/, '') : '未分类';
      }

      // 使用商品名称作为键
      productStatsMap.set(product.name, {
        id: product.id,
        name: product.name,
        category: categoryName,
        categoryId: categoryId || product.category_id,
        stock: totalStock,
        unit: product.unit,
        sales: 0,
        amount: 0
      })
    })
    console.log('fetchHotProducts: 商品统计Map初始化完成，共有商品数:', productStatsMap.size)
    console.log('fetchHotProducts: 商品统计Map中的所有商品名称:', Array.from(productStatsMap.keys()))
    console.log('fetchHotProducts: 商品统计Map示例:', Array.from(productStatsMap.values()).slice(0, 2))

    // 2. 获取指定时间范围内的销售订单
    const startDate = new Date()
    if (hotProductsTimeRange.value === 'week') {
      startDate.setDate(startDate.getDate() - 7)
    } else {
      startDate.setDate(1) // 本月初
    }
    console.log('fetchHotProducts: 查询订单的时间范围:', {
      start_date: startDate.toISOString().split('T')[0],
      end_date: new Date().toISOString().split('T')[0]
    })

    console.log('fetchHotProducts: 正在获取销售订单数据...')
    const ordersResponse = await axios({
      method: 'get',
      url: '/api/sales-orders',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    console.log('fetchHotProducts: 订单API响应数据:', ordersResponse.data)

    // 处理订单数据
    const orders = ordersResponse.data?.data?.items || 
                   ordersResponse.data?.items || 
                   ordersResponse.data?.results || 
                   (Array.isArray(ordersResponse.data) ? ordersResponse.data : [])
    console.log('fetchHotProducts: 解析后的订单数组长度:', orders.length)
    console.log('fetchHotProducts: 订单数据示例:', orders.slice(0, 2))
    
    // 3. 统计每个商品的销量和销售额
    console.log('fetchHotProducts: 开始统计商品销量...')
    orders.forEach((order, orderIndex) => {
      // 只统计已付款、已发货和已完成的订单，并且在选定时间范围内的订单
      if (!['paid', 'shipped', 'completed'].includes(order.status)) {
        console.log(`fetchHotProducts: 跳过订单 ${order.order_number}，状态为 ${order.status}`)
        return
      }

      // 检查订单支付时间是否在选定范围内
      const paymentTime = order.payment_time ? new Date(order.payment_time) : null;
      if (!paymentTime || paymentTime < startDate || paymentTime > new Date()) {
        console.log(`fetchHotProducts: 跳过订单 ${order.order_number}，支付时间不在范围内`)
        return
      }

      console.log(`fetchHotProducts: 处理第 ${orderIndex + 1} 个订单:`, order.order_number)
      // 尝试从不同位置获取订单项
      const orderItems = order.items || order.order_items || [];
      console.log(`fetchHotProducts: 订单 ${order.order_number || order.id} 的商品项:`, orderItems)
      
      // 如果没有找到订单项，可能需要检查嵌套结构
      if (!orderItems || orderItems.length === 0) {
        console.warn(`fetchHotProducts: 订单 ${order.order_number || order.id} 没有商品项或结构不符合预期`)
        // 尝试打印完整订单以便调试
        console.log('fetchHotProducts: 完整订单数据:', order)
        return
      }
      
      orderItems.forEach((item, itemIndex) => {
        // 尝试从不同位置获取商品名称
        let productName = null;

        // 1. 直接从商品项的product_name获取
        if (item.product_name) {
          productName = item.product_name;
        } 
        // 2. 从product对象的name属性获取
        else if (item.product) {
          if (typeof item.product === 'object' && item.product !== null) {
            productName = item.product.name;
          } 
          // 3. 如果product是ID，尝试从productStatsMap中按ID查找
          else if (typeof item.product === 'number' || typeof item.product === 'string') {
            // 尝试从产品ID映射到产品名称
            const productId = item.product.toString();
            // 查找对应ID的产品
            const foundProduct = Array.from(productStatsMap.values()).find(p => p.id.toString() === productId);
            if (foundProduct) {
              productName = foundProduct.name;
              console.log(`fetchHotProducts: 通过ID '${productId}' 找到商品名称: "${productName}"`);
            }
          }
        }
        // 4. 直接从name属性获取
        else if (item.name) {
          productName = item.name;
        }

        console.log(`fetchHotProducts: 尝试匹配商品: "${productName}"`, item)
        
        if (!productName || !productStatsMap.has(productName)) {
          console.warn(`fetchHotProducts: 订单 ${order.order_number || order.id} 的第 ${itemIndex + 1} 个商品未找到匹配记录:`, {
            item,
            productName,
            availableProducts: Array.from(productStatsMap.keys())
          })
          return
        }

        const productStats = productStatsMap.get(productName)
        const quantity = parseFloat(item.quantity) || 0
        const unitPrice = parseFloat(item.unit_price) || 0
        
        const oldSales = productStats.sales
        const oldAmount = productStats.amount
        
        productStats.sales += quantity
        productStats.amount += quantity * unitPrice
        
        console.log(`fetchHotProducts: 更新商品 ${productStats.name} 销量:`, {
          oldSales,
          addedQuantity: quantity,
          newSales: productStats.sales,
          oldAmount,
          addedAmount: quantity * unitPrice,
          newAmount: productStats.amount
        })
      })
    })

    // 4. 转换为数组并按销量排序，获取前10名
    console.log('fetchHotProducts: 开始排序商品销量...')
    const allProducts = Array.from(productStatsMap.values())
    console.log('fetchHotProducts: 所有商品的销量统计:', allProducts.map(p => ({
      name: p.name,
      sales: p.sales,
      amount: p.amount
    })))
    
    const sortedProducts = allProducts
      .filter(product => product.sales > 0)  // 只显示有销量的商品
      .sort((a, b) => b.sales - a.sales)
      .slice(0, 10)
    
    console.log('fetchHotProducts: 最终的Top 10热销商品:', sortedProducts.map(p => ({
      name: p.name,
      sales: p.sales,
      amount: p.amount,
      category: p.category,
      stock: p.stock
    })))

        hotProducts.value = sortedProducts
    console.log('fetchHotProducts: 热销商品数据更新完成')
  } catch (error) {
    console.error('fetchHotProducts: 获取热销商品数据失败:', error)
    console.error('fetchHotProducts: 错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status
    })
    ElMessage.error('获取热销商品数据失败')
    hotProducts.value = []
  } finally {
    hotProductsLoading.value = false
  }
}

// 计算移动平均预测
const calculateMovingAverage = (data, windowSize = 3) => {
  const result = []
  for (let i = 0; i < data.length; i++) {
    if (i < windowSize - 1) {
      result.push(null)
      continue
    }
    let sum = 0
    for (let j = 0; j < windowSize; j++) {
      sum += data[i - j]
    }
    result.push(sum / windowSize)
  }
  return result
}

// 预测下一天的值
const predictNextDay = (data) => {
  if (data.length < 3) return null
  const lastThreeDays = data.slice(-3)
  const weights = [0.5, 0.3, 0.2] // 权重：最近的一天权重最大
  return lastThreeDays.reduce((sum, value, index) => sum + value * weights[index], 0)
}

// 获取销售趋势数据
const fetchSalesTrend = async () => {
  salesTrendLoading.value = true
  console.log('fetchSalesTrend: Start fetching sales trend data...')
  try {
    const token = getToken()
    if (!token) {
      ElMessage.error('未登录或登录已过期')
      salesTrendLoading.value = false
      return
    }

    // 计算日期范围
    const now = new Date()
    const startDate = new Date(now)
    startDate.setDate(now.getDate() - (salesTrendTimeRange.value === 'week' ? 7 : 30))

    // 获取订单数据
    const response = await axios({
      method: 'get',
      url: '/api/sales-orders/',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    const orders = response.data?.data?.items || []
    console.log('fetchSalesTrend: Fetched orders count:', orders.length)

    // 过滤有效订单
    const validOrders = orders.filter(order => {
      const orderDate = new Date(order.payment_time)
      return orderDate >= startDate && 
             orderDate <= now && 
             ['paid', 'shipped', 'completed'].includes(order.status)
    })
    console.log('fetchSalesTrend: Valid orders count:', validOrders.length)

    // 生成日期序列
    const dates = []
    const currentDate = new Date(startDate)
    while (currentDate <= now) {
      dates.push(currentDate.toISOString().split('T')[0])
      currentDate.setDate(currentDate.getDate() + 1)
    }

    // 初始化每日数据
    const dailyData = {}
    dates.forEach(date => {
      dailyData[date] = { orders: 0, sales: 0 }
    })

    // 统计每日数据
    validOrders.forEach(order => {
      const orderDate = new Date(order.payment_time).toISOString().split('T')[0]
      if (dailyData[orderDate]) {
        dailyData[orderDate].orders++
        dailyData[orderDate].sales += parseFloat(order.total_amount) || 0
      }
    })

    // 转换为数组格式
    const trendData = dates.map(date => ({
      date,
      orders: dailyData[date].orders,
      sales: dailyData[date].sales
    }))

    // 计算移动平均
    const orderValues = trendData.map(item => item.orders)
    const salesValues = trendData.map(item => item.sales)
    
    const orderMA = calculateMovingAverage(orderValues)
    const salesMA = calculateMovingAverage(salesValues)

    // 预测下一天的值
    const nextDayOrderPrediction = predictNextDay(orderValues)
    const nextDaySalesPrediction = predictNextDay(salesValues)

    // 添加预测数据
    if (nextDayOrderPrediction !== null && nextDaySalesPrediction !== null) {
      const nextDate = new Date(now)
      nextDate.setDate(now.getDate() + 1)
      const nextDateStr = nextDate.toISOString().split('T')[0]
      
      trendData.push({
        date: nextDateStr,
        orders: nextDayOrderPrediction,
        sales: nextDaySalesPrediction,
        isPrediction: true
      })
    }

    salesTrend.value = trendData
    updateSalesTrendChart()

  } catch (error) {
    console.error('Error fetching and processing sales trend:', error)
    ElMessage.error('获取或处理销售趋势数据失败')
  } finally {
    salesTrendLoading.value = false
  }
}

// 更新销售趋势图表选项
const updateSalesTrendChart = () => {
  const dates = salesTrend.value.map(item => item.date)
  const orderData = salesTrend.value.map(item => item.orders)
  const salesData = salesTrend.value.map(item => item.sales)
  
  // 分离实际数据和预测数据
  const actualOrderData = orderData.slice(0, -1)
  const actualSalesData = salesData.slice(0, -1)
  const predictionOrderData = Array(orderData.length - 1).fill(null).concat(orderData[orderData.length - 1])
  const predictionSalesData = Array(salesData.length - 1).fill(null).concat(salesData[salesData.length - 1])

  salesTrendOption.value = {
    title: {
      text: '销售趋势分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['订单数量', '销售额'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '订单数量',
        position: 'left'
      },
      {
        type: 'value',
        name: '销售额',
        position: 'right',
        axisLabel: {
          formatter: '{value} 元'
        }
      }
    ],
    series: [
      {
        name: '订单数量',
        type: 'bar',
        data: orderData,
        itemStyle: {
          color: function(params) {
            // 如果是预测数据（最后一个点），使用特殊颜色
            return params.dataIndex === orderData.length - 1 ? '#ff9800' : '#409EFF'
          }
        }
      },
      {
        name: '销售额',
        type: 'line',
        smooth: true,
        data: salesData,
        yAxisIndex: 1,
        itemStyle: {
          color: function(params) {
            // 如果是预测数据（最后一个点），使用特殊颜色
            return params.dataIndex === salesData.length - 1 ? '#ff9800' : '#67C23A'
          }
        },
        lineStyle: {
          color: '#67C23A'
        }
      }
    ]
  }
}

// 获取分类样式
const getCategoryType = (category) => {
  const types = {
    '绿色蔬菜': 'success',
    '新鲜水果': 'warning',
    '优质肉类': 'danger',
    '新鲜海鲜': 'info'
  }
  return types[category] || 'info'
}

// 获取库存状态类型
const getStockStatusType = (stock) => {
  if (stock >= 100) return 'success'
  if (stock >= 50) return ''
  return 'danger'
}

// 获取库存状态文本
const getStockStatusText = (stock) => {
  if (stock >= 100) return '充足'
  if (stock >= 50) return '正常'
  return '偏低'
}

// 修改模板中的显示文本
const getStatisticLabel = (type) => {
  if (type === 'orders') {
    return `较上月同期 ${statistics.value.orderGrowth > 0 ? '+' : ''}${statistics.value.orderGrowth}% | 环比 ${statistics.value.orderWoWGrowth > 0 ? '+' : ''}${statistics.value.orderWoWGrowth}%`
  } else if (type === 'sales') {
    return `较上月同期 ${statistics.value.salesGrowth > 0 ? '+' : ''}${statistics.value.salesGrowth}% | 环比 ${statistics.value.salesWoWGrowth > 0 ? '+' : ''}${statistics.value.salesWoWGrowth}%`
  } else if (type === 'customers') {
    return '本月新增'
  }
  return ''
}

// 监听时间范围变化
watch(hotProductsTimeRange, () => {
  fetchHotProducts()
})

watch(salesTrendTimeRange, () => {
  fetchSalesTrend()
})

// 页面加载时获取数据
onMounted(() => {
  fetchDashboardStats()
  fetchHotProducts()
  fetchSalesTrend()
})
</script>

<style scoped>
.salesman-dashboard {
  padding: 20px;
}

.statistics-cards .el-card {
  margin-bottom: 20px;
}

.card-header-with-icon {
  display: flex;
  align-items: center;
}

.card-header-with-icon .el-icon {
  margin-right: 8px;
  font-size: 20px;
}

.statistic-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.statistic-label {
  font-size: 14px;
  color: #909399;
}

.statistic-label .up {
  color: #67c23a;
}

.statistic-label .down {
  color: #f56c6c;
}

.hot-products-card,
.trend-chart-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 400px;
}

.chart {
  height: 100%;
  width: 100%;
}
</style>